#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <cassert>
#include <fstream>
#include <jsoncpp/json/json.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "../comm/httplib.h"
// #include "oj_model.hpp"
#include "oj_model2.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace ns_util;
    using namespace ns_log;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;
    // 提供服务的主机
    class Machine
    {
    public:
        std::string _ip;  // 编译服务的ip
        int _port;        // 编译服务的端口号
        uint64_t _load;   // 编译服务的负载
        std::mutex *_mtx; // mutex是禁止拷贝的, 这里使用指针
    public:
        Machine() : _ip(""), _port(0), _load(0), _mtx(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        // 增加主机负载
        void IncLoad()
        {
            if (_mtx)
                _mtx->lock();
            _load++;
            if (_mtx)
                _mtx->unlock();
        }
        // 减少主机负载
        void DecLoad()
        {
            if (_mtx)
                _mtx->lock();
            if (_load > 0)
                _load--;
            if (_mtx)
                _mtx->unlock();
        }
        // 获取主机负载
        uint64_t Load()
        {
            uint64_t load;
            if (_mtx)
                _mtx->lock();
            load = _load;
            if (_mtx)
                _mtx->unlock();
            return load;
        }
        // 重设主机负载
        void ResetLoad()
        {
            if (_mtx)
                _mtx->lock();
            _load = 0;
            if (_mtx)
                _mtx->unlock();
        }
    };

    const std::string service_machine = "./conf/service_machine.conf";
    // 负载均衡
    class LoadBalance
    {
    private:
        std::vector<Machine> _machines; // 可以提供编译服务的所有主机, 下标充当主机id
        std::vector<int> _online;       // 所有在线的主机id
        std::vector<int> _offline;      // 所有离线的主机id
        std::mutex _mtx;                // 保证LoadBalance的数据安全
    public:
        LoadBalance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功" << "\n";
        }
        ~LoadBalance()
        {
        }

    public:
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载：" << machine_conf << " 失败" << "\n";
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分 " << line << " 失败" << "\n";
                    continue;
                }
                Machine m;
                m._ip = tokens[0];
                m._port = atoi(tokens[1].c_str());
                m._load = 0;
                m._mtx = new std::mutex();
                _online.push_back(_machines.size());
                _machines.push_back(m);
            }

            in.close();
            return true;
        }
        bool SmartChoice(int *id, Machine **m)
        {
            // 1. 选择主机(更新主机的负载)
            // 2. 可能需要离线该主机
            _mtx.lock();

            if (_online.size() == 0)
            {
                LOG(FATAL) << "所有后端编译主机已全部离线" << "\n";
                _mtx.unlock();
                return false;
            }

            // 负载均衡的算法
            // 1. 随机数+hash
            // 2. 轮询+hash
            uint64_t min_load = _machines[_online[0]].Load();
            *id = _online[0];
            *m = &_machines[_online[0]];
            for (int i = 1; i < _online.size(); i++)
            {
                uint64_t cur_load = _machines[_online[i]].Load();
                if (min_load > cur_load)
                {
                    min_load = cur_load;
                    *id = _online[i];
                    *m = &_machines[_online[i]]; // 这里使用取地址&可以减少一次拷贝
                }
            }

            _mtx.unlock();
            return true;
        }
        void OfflineMachine(int which)
        {
            _mtx.lock();
            for (auto iter = _online.begin(); iter != _online.end(); iter++)
            {
                if (*iter == which)
                {
                    _machines[which].ResetLoad();
                    _offline.push_back(*iter);
                    _online.erase(iter);
                    break; // break的存在避免了发生迭代器失效
                }
            }
            _mtx.unlock();
        }

        // 统一上线
        void OnlineMachine()
        {
            _mtx.lock();
            _online.insert(_online.end(), _offline.begin(), _offline.end());
            _offline.erase(_offline.begin(), _offline.end());
            _mtx.unlock();
        }

        // for test
        void ShowMachine()
        {
            _mtx.lock();
            std::cout << "在线主机列表：";
            for (auto &id : _online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "离线主机列表：";
            for (auto &id : _offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;

            _mtx.unlock();
        }
    };

    const std::string question_path = "./questions/";
    const std::string header_temp = "/header_temp.cpp";
    class Control
    {
    private:
        Model _model;              // 提供后台数据
        View _view;                // 提供网页渲染
        LoadBalance _load_balance; // 核心负载均衡器
    public:
        Control()
        {
        }
        ~Control()
        {
        }

    public:
        void RecoveryMachine()
        {
            _load_balance.OnlineMachine();
            LOG(INFO) << "所有主机已上线" << "\n";
        }

        bool AllQuestions(std::string *html)
        {
            std::vector<Question> all;
            if (_model.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const Question &q1, const Question &q2)
                     { return atoi(q1.number.c_str()) < atoi(q2.number.c_str()); });
                // 获取所有题目信息成功，将所有题目数据构建成网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                return false;
            }
            return true;
        }

        bool OneQuestion(const std::string &number, std::string *html)
        {
            Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 构建网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目: " + number + " 不存在!";
                return false;
            }
            return true;
        }

        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 0. 根据题目编号，拿到题目细节
            Question q;
            _model.GetOneQuestion(number, &q);
            // 1. in_json进行反序列化，得到题目id，用户提交的源代码，input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 2. 拼接用户代码和测试用例代码
            Json::Value compile_value;
            compile_value["code"] = code + q.tail;
#ifndef COMPILER_ONLINE
            std::string header_temp_path = question_path + q.number + header_temp;
            if(!FileUtil::IsFileExists(header_temp_path))
                LOG(ERROR) << header_temp_path << " 该文件不存在" << "\n";
            else
            {
                if(!FileUtil::WriteFile(header_temp_path, code))
                    LOG(ERROR) << "向" << header_temp_path << "文件写入失败" << "\n";
            }
            compile_value["code"] = q.tail;
#endif
            compile_value["input"] = in_value["input"].asString();
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 3. 选择负载最低的主机(差错处理)
            // 规则：一直选择，直到有主机可用，否则说明全部挂掉了
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_balance.SmartChoice(&id, &m))
                {
                    break;
                }
                m->IncLoad();
                LOG(INFO) << "选择主机成功, id: " << id << " 详细: " << m->_ip << ":" << m->_port << " 当前负载: " << m->Load() << "\n";

                // 4. 发起http请求，得到结果
                Client cl(m->_ip, m->_port);
                if (auto res = cl.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    m->DecLoad();
                    if (res->status == 200)
                    {
                        // 5. 将结果赋值给out_json
                        *out_json = res->body;
                        LOG(INFO) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前选择的主机id: " << id << " 详细: " << m->_ip << ":" << m->_port << " 可能已经离线" << "\n";
                    _load_balance.OfflineMachine(id);
                    _load_balance.ShowMachine();
                }
            }
        }
    };
}